package labox.innovation.gameserver.network.clientpackets;

import labox.innovation.gameserver.model.FuzeWorld;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.network.SystemMessageId;
import labox.innovation.gameserver.network.serverpackets.ActionFailed;
import labox.innovation.gameserver.network.serverpackets.SystemMessage;
import labox.innovation.gameserver.network.serverpackets.TradeDone;

/**
 *  回应交易请求的协议
 *  客户端请求
 * @author zjj
 * 
 */
public final class AnswerTradeRequest extends L2GameClientPacket {
	private static final String _C__74_ANSWERTRADEREQUEST = "[C] 0x74 AnswerTradeRequest";

	//private static Logger _log = Logger.getLogger(AnswerTradeRequest.class.getName());

	private int _response; //0:不交易 1交易

	@Override
	protected void readImpl() {
		_response = readByte();
	}

	@Override
	protected void runImpl() {
		FuzePcInstance player = getClient().getActiveChar();
		if (player == null)
			return;

		if (!player.getAccessLevel().allowTransaction()) {
			player.sendPacket(new SystemMessage(SystemMessageId.YOU_ARE_NOT_AUTHORIZED_TO_DO_THAT));
			sendPacket(ActionFailed.STATIC_PACKET);
			return;
		}

		FuzePcInstance partner = player.getActiveRequester();
		if (partner == null) {
			// Trade partner not found, cancel trade
			player.sendPacket(new TradeDone(0));
			SystemMessage msg = new SystemMessage(SystemMessageId.TARGET_IS_NOT_FOUND_IN_THE_GAME);
			player.sendPacket(msg);
			player.setActiveRequester(null);
			msg = null;
			return;
		} else if (player.getKnownList().getKnownCharacters().get(partner.getObjectId()) == null) {
			// Trade partner not found, cancel trade
			player.sendPacket(new TradeDone(0));
			SystemMessage msg = new SystemMessage(SystemMessageId.TARGET_IS_NOT_FOUND_IN_THE_GAME);
			player.sendPacket(msg);
			player.setActiveRequester(null);
			msg = null;
			return;
		}

		if (_response == 1 && !partner.isRequestExpired())
			player.startTrade(partner);
		else {
			SystemMessage msg = new SystemMessage(SystemMessageId.C1_DENIED_TRADE_REQUEST);
			msg.addString(player.getName());
			partner.sendPacket(msg);
			msg = null;
		}

		// Clears requesting status
		player.setActiveRequester(null);
		partner.onTransactionResponse();
	}

	/* (non-Javadoc)
	 * @see labox.innovation.gameserver.clientpackets.ClientBasePacket#getType()
	 */
	@Override
	public String getType() {
		return _C__74_ANSWERTRADEREQUEST;
	}
}
